import {
  createRouter,
  createWebHistory,
  RouteRecordRaw,
  createWebHashHistory,
} from "vue-router";
import axios from "axios";
import {getCurUser, getRouterList, getRouterList1} from "@/http/common";
import HomeView from "../layout/HomeView.vue";

const routes: Array<RouteRecordRaw> = [
  {
    path: "/login",
    name: "login",
    component: () => import("../layout/Login.vue"),
  },
];

const router = createRouter({
  // history: createWebHistory(process.env.BASE_URL), //H5-history路由
  history: createWebHashHistory(), //哈希路由
  routes,
});
// 路由守卫

let firstRegisterRoute = true;
router.beforeEach(async (to, from, next) => {
  if (firstRegisterRoute) {

    const ss: any = await axios.get("api/user/current",{
      headers:{
        // @ts-ignore
        Authorization:window.localStorage.getItem("token")
      }
    });
    if(ss.data.code !== 200){
      if (to.path === "/login") {
        next();
      } else {
        next("/login");
      }
    }

    localStorage.setItem("userInfo",JSON.stringify(ss.data.data))



    const dataList: any = await getRouterList1(ss.data.data.id);
    const arr: any = [];

    //获取动态路由
    dataList.menu.forEach((item: any) => {
      if(item.component){
      arr.push({
        path: item.path,
        name: item.name,
      //  redirect:item.redirect,
        component: () => import(`../views/${item.component}.vue`),
      });
      }

      if (item.children) {
        item.children.forEach((item1: any) => {
          arr.push({
            path: item1.path,
            name: item1.name,
            component: () => import(`../views/${item1.component}.vue`),
          });
        });
      }
    });

    console.log(arr)
    router.addRoute({
      path: "/",
      name: "home",
      component: HomeView,
      redirect: arr[0].path,
      children: arr,
    });
    firstRegisterRoute = false;
    next(to.path);
    return;
  }
  //我在这里模仿了一个获取用户信息的方法
  const isLogin = window.localStorage.getItem("token");
  if (isLogin) {
    //如果用户信息存在则往下执行。
    next();
  } else {
    //如果用户token不存在则跳转到login页面
    if (to.path === "/login") {
      next();
    } else {
      next("/login");
    }
  }
});

export default router;
